package com.neusoft.databus.policy.utils;

import java.util.Arrays;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.databus.policy.enums.EventStatus;
import com.neusoft.databus.policy.enums.PolicyType;
import com.neusoft.databus.policy.repository.EventRepository;

/**
 * 告警数量计算
 *
 * @author naxiang
 */
@Component
public class EventCountUtil implements CommandLineRunner {
    @Autowired
    private EventRepository eventRepository;
    private final Map<PolicyType, Integer> eventCounts = Maps.newHashMap();

    /**
     * 告警数量计算
     *
     * @param policyType
     * @param status
     */
    public void eventCount(final PolicyType policyType, final EventStatus status) {
        Integer eventCount = this.eventCount(policyType);
        if (EventStatus.FIXED.equals(status)) {
            eventCount--;
        } else if (EventStatus.UNFIXED.equals(status)) {
            eventCount++;
        }
        this.eventCounts.put(policyType, eventCount);
    }

    /**
     * 获取告警数量
     *
     * @param policyType
     * @return
     */
    public Integer eventCount(final PolicyType policyType) {
        Integer eventCount = 0;
        if (this.eventCounts.containsKey(policyType)) {
            eventCount = this.eventCounts.get(policyType);
        }
        return eventCount;
    }

    /**
     * 查询告警数量
     *
     * @param policyType
     * @return
     */
    private Integer getEventCount(final PolicyType policyType) {
        final Searchable searchable = new Searchable();
        searchable.put("type", policyType);
        searchable.put("status", EventStatus.UNFIXED);
        final Integer eventCount = this.eventRepository.search(searchable).size();
        return eventCount;
    }

    /**
     * 加载告警个数
     */
    @Override
    public void run(final String... args) throws Exception {
        Arrays.asList(PolicyType.values()).stream().forEach(t -> {
            this.eventCounts.put(t, this.getEventCount(t));
        });
    }
}
